package com.lfl.util;

import com.alibaba.druid.pool.DruidDataSource;

import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @program: JavaEE-EFD
 * @description: 手写数据库执行类, 手写 druid数据库连接池
 * @author: fengjd
 * @create: 2022-07-27 17:36
 **/
public class DBUtil {

    private static String driveName;
    private static String url;
    private static String user;
    private static String password;

    private static DruidDataSource druid;
    private static Integer initialSize;
    private static Integer maxActive;
    private static Integer minIdle;
    private static Integer maxWait;

    static {
        try {
            Properties prop = PropertyUtil.getInstance();
            driveName = prop.getProperty("driveName");
            url = prop.getProperty("url");
            user = prop.getProperty("user");
            password = prop.getProperty("password");

            /* 获取连接池信息 */
            initialSize = Integer.parseInt(prop.getProperty("initialSize"));
            maxActive = Integer.parseInt(prop.getProperty("maxActive"));
            minIdle = Integer.parseInt(prop.getProperty("minIdle"));
            maxWait = Integer.parseInt(prop.getProperty("maxWait"));

            /*配置基本信息*/
            druid.setDriverClassName(driveName);
            druid.setUrl(url);
            druid.setUsername(user);
            druid.setPassword(AesUtil.decrypt(password, "woniu"));

            /* 连接池信息 */
            druid.setInitialSize(initialSize);
            druid.setMaxActive(maxActive);
            druid.setMinIdle(minIdle);
            druid.setMaxWait(maxWait);

            PropertyUtil.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取数据库连接
     *
     * @return
     */
    public static Connection getConnection() {
        try {
            Connection connection = druid.getConnection();
            return connection;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 关闭数据库连接
     * @param connection
     */
    public static void close(Connection connection) {
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }
}
